package com.zeratul.common.event.core.handler.redis;

import com.zeratul.common.event.base.BasePublishHandler;
import com.zeratul.common.event.domain.ZtEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Redis消息发布者
 */
public class RedisPublishHandler implements BasePublishHandler {

    @SuppressWarnings("rawtypes")
    @Autowired
    @Qualifier("eventRedisTemplate")
    private RedisTemplate<String, byte[]> redisTemplate;

    /**
     * 执行事件发送
     *
     * @param ztEvent    - 事件对象
     * @param eventBytes - 事件对象序列化后的字节数组
     */
    @Override
    public <T> void doSendEvent(ZtEvent<T> ztEvent, byte[] eventBytes) {
        try {
            //使用Redis将消息发送出去
            redisTemplate.convertAndSend(ztEvent.getTopic(), eventBytes);
            //消息确认
            sendCallback(ztEvent, null);
        } catch (Exception e) {
            log.error("【事件总线】消息发布者发送失败！消息内容：{}", ztEvent, e);
            sendCallback(ztEvent, e);
        }
    }
}
